import { defineStore } from 'pinia';
import axios from 'axios';

interface Station {
    stationId: string;
    stationName: string;
}
interface State {
    curStation: Station;
    stationList: Station[];
}
interface Getter {
    stationId: (state: State) => string;
}
interface Action {
    load: () => Promise<Station[]>;
    change: (station: Station) => void;
}

export const useStation = defineStore<string, State, Getter, Action>(
    'station',
    {
        state: () => {
            return {
                curStation: JSON.parse(
                    localStorage.getItem('enric-station') || '{}'
                ),
                stationList: [],
            };
        },
        getters: {
            stationId(state: State) {
                return state.curStation?.stationId;
            },
        },
        actions: {
            async load() {
                const data: any = await axios.post('/api/v1/user/stations');
                this.stationList = data.result || [];
                this.curStation = this.curStation.stationId&&this.stationList.map(item=>item.stationId).includes(this.curStation.stationId)
                    ? this.curStation
                    : this.stationList[0];

                return data.result;
            },
            change(station) {
                localStorage.setItem('enric-station', JSON.stringify(station));
                this.curStation = station;
                // 更新用于请求
                window.location.reload();
            },
        },
    }
);
export default useStation;
